<template>
  <div class="app-container">
    <el-form :inline="true" :model="formParams" v-show="showSearch" class="demo-form-inline">
      <el-form-item label="订单号">
        <el-input
          v-model.trim="formParams.orderSn"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单商户">
        <el-input
          v-model.trim="formParams.enterpriseName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          value-format="x"
          v-model="formParams._date"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="地区筛选">
        <el-cascader
          placeholder="请选择"
          v-model="formParams.provinces"
          :options="district"
          filterable
          clearable
          :collapse="true"
          :props="props"
          collapse-tags
        />
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleReset()">重置</el-button>
        <el-button type="primary" @click="handleQuery()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" justify="end">
      <el-button v-hasPermi="['order:enterprise:export']" type="primary" @click="handleExport()"
        >批量导出筛选数据</el-button
      >
    </el-row>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div style="margin: 20px 0 0 70px">{{ orderingDate }}订餐汇总数据</div>
    <el-row :gutter="20" v-if="packageAllData.length">
      <el-col
        :span="6"
        style="
          display: flex;
          justify-content: center;
          align-items: center;
          color: #666;
          height: 50px;
        "
        v-for="item in packageAllData"
        :key="item.comboName"
      >
        {{ `${item.comboName}*${item.comboNum}` }}</el-col
      >
    </el-row>
    <div v-else style="color: #909399; text-align: center; height: 50px; font-size: 14px"
      >暂无数据</div
    >

    <el-table v-loading="loading" :data="list">
      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="下单商户" align="center" prop="enterpriseName" />
      <el-table-column label="套餐总数（份）" align="center" prop="comboNum" />
      <el-table-column label="套餐总金额" align="center" prop="money" />
      <el-table-column label="下单时间" align="center" prop="createTime" />
      <el-table-column label="支付方式" align="center" prop="payWay" />
      <el-table-column label="企业地址" align="center" prop="enterpriseSite" />
      <el-table-column label="套餐详情" align="center" width="150">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['order:enterprise:packageDetails']"
            link
            type="primary"
            @click="details(row, true)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" width="150" fixed="right">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['order:enterprise:details']"
            link
            type="primary"
            @click="details(row, false)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="formParams.pageNum"
      v-model:limit="formParams.pageSize"
      @pagination="getList()"
    />

    <orderDialog ref="orderDialogRef" />
    <packageDialog ref="packageDialogRef" />
  </div>
</template>
<script setup>
import useGlobalStore from '@/store/modules/global'
import orderDialog from './components/orderDialog.vue'
import packageDialog from './components/packageDialog.vue'
import { postPackageDataSummaryApi, postEnterpriseOrderListApi } from '@/api/order'
import { formatDate1 } from '@/utils'

const { proxy } = getCurrentInstance()
const globalStore = useGlobalStore()
const district = computed(() => {
  console.log(globalStore.district)
  return globalStore.district
})

const orderingDate = ref('今日')
const orderDialogRef = ref()
const packageDialogRef = ref()
const showSearch = ref(true)
const props = { multiple: true, value: 'label', label: 'label', children: 'children' }
const total = ref(0)
const loading = ref(false)
const formParams = ref({
  orderSn: null,
  enterpriseName: null,
  startTime: null,
  endTime: null,
  _date: null,
  provinces: null,
  pageNum: 1,
  pageSize: 10
})
const list = ref([])
const packageAllData = ref([])
function handleReset() {
  formParams.value = {
    orderSn: null,
    enterpriseName: null,
    startTime: null,
    endTime: null,
    _date: null,
    provincess: null,
    pageNum: 1,
    pageSize: 10
  }
  orderingDate.value = '今日'
  getList()
  console.log(22222)
}
function handleQuery() {
  console.log(formParams.value._date)

  if (formParams.value._date?.length && formParams.value._date[0] === formParams.value._date[1]) {
    formParams.value._date[1] = formParams.value._date[1] + 86399000
  }
  formParams.value.pageNum = 1
  if (formParams.value._date?.length) {
    const _data = formParams.value._date.map((item) => {
      return formatDate1(item)
    })
    orderingDate.value = _data.join('至')
  } else if (
    formParams.value.orderSn ||
    formParams.value.enterpriseName ||
    formParams.value.provinces?.length
  ) {
    orderingDate.value = ''
  }
  getList()
  console.log(11111111)
}

/** 导出列表 */
function handleExport() {
  if (formParams.value._date?.length > 0) {
    formParams.value.startTime = formParams.value._date[0]
    formParams.value.endTime = formParams.value._date[1]
  }
  const provinces = handleAreaName(formParams.value.provinces)
  proxy.download(
    '/group/enterpriseOrder/derive/enterpriseOrder',
    { ...formParams.value, provinces },
    `企业用户订单列表${new Date().getTime()}.xlsx`
  )
  const params = {
    orderSn: formParams.value.orderSn,
    enterpriseName: formParams.value.enterpriseName,
    startTime: !orderingDate.value
      ? formParams.value.startTime
      : orderingDate.value === '今日'
      ? dayStartTime.value.top
      : formParams.value.startTime,
    endTime: !orderingDate.value
      ? formParams.value.endTime
      : orderingDate.value === '今日'
      ? dayStartTime.value.bottom
      : formParams.value.endTime,
    provinces
  }
  proxy.download(
    '/group/enterpriseOrder/derive/comboCollect',
    { ...params },
    `订餐汇总数据${new Date().getTime()}.xlsx`
  )
}
/** 获取列表数据 */
function getList() {
  if (formParams.value._date?.length > 0) {
    formParams.value.startTime = formParams.value._date[0]
    formParams.value.endTime = formParams.value._date[1]
  }
  const provinces = handleAreaName(formParams.value.provinces)
  getPackageDataSummary(provinces)
  loading.value = true
  postEnterpriseOrderListApi({ ...formParams.value, provinces })
    .then((res) => {
      console.log(res.data.rows)
      total.value = res.data.total || 0
      list.value = res.data.list?.map((item) => {
        return {
          ...item,
          payWay: item.payWay === 1 ? '微信支付' : item.payWay === 2 ? '微信二维码' : '余额'
        }
      })
    })
    .finally(() => {
      loading.value = false
    })
  console.log(provinces)
}
/**套餐数据汇总 */
function getPackageDataSummary(provinces) {
  const params = {
    orderSn: formParams.value.orderSn,
    enterpriseName: formParams.value.enterpriseName,
    startTime: !orderingDate.value
      ? formParams.value.startTime
      : orderingDate.value === '今日'
      ? dayStartTime.value.top
      : formParams.value.startTime,
    endTime: !orderingDate.value
      ? formParams.value.endTime
      : orderingDate.value === '今日'
      ? dayStartTime.value.bottom
      : formParams.value.endTime,
    provinces
  }
  postPackageDataSummaryApi(params).then((res) => {
    console.log(res)
    packageAllData.value = res.data || []
  })
}
/**处理区域名称 */
function handleAreaName(arr = []) {
  if (!arr?.length) return null
  return arr.map((item) => {
    return item.join('/')
  })
}
const dayStartTime = ref({
  top: null,
  bottom: null
})
function getTodayStartTimestamp() {
  const today = new Date()
  today.setHours(0, 0, 1, 0)
  const startOfDayTimestamp = today.getTime()

  today.setHours(23, 59, 59, 0)
  const endOfDayTimestamp = today.getTime()

  dayStartTime.value = {
    top: startOfDayTimestamp,
    bottom: endOfDayTimestamp
  }
}
/**进入详情页面，根据 type 判断是订单详情还是套餐详情 */
function details(row, type) {
  if (type) {
    packageDialogRef.value.init(row.orderSn)
  } else {
    orderDialogRef.value.init(row.orderSn)
  }
}
getTodayStartTimestamp()
getList()
</script>
<style lang="scss" scoped>
.el-input {
  width: 215px;
}
</style>
